package org.zjx.service;

import org.zjx.battle.BattleEngineFactory;
import org.zjx.battle.BattleManager;
import org.zjx.battle.IBattleEngine;
import org.zjx.battle.entity.Battle;
import org.zjx.battle.entity.Enemy;
import org.zjx.common.command.ICommand;
import org.zjx.common.command.battle.ExitCommand;
import org.zjx.common.entity.Quest;
import org.zjx.common.model.RouteProperties;
import org.zjx.common.service.DecisionService;
import org.zjx.task.TaskManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class DecisionServiceImpl implements DecisionService {
    @Override
    public ICommand decide(RouteProperties routeProperties) {
        if (routeProperties == null || routeProperties.getPlayerId() == null || routeProperties.getPlayerId().isEmpty())
            return new ExitCommand();

        //预更新战场状态

        if (routeProperties.isInBattle()) {
            Battle battle = BattleManager.getInstance().updateBattleRouteProperties(routeProperties);
            IBattleEngine battleEngine = BattleEngineFactory.getEngineForWar(battle);
            return battleEngine.analyzeAndGenerateCommands(routeProperties, battle);
        } else {
            return TaskManager.getInstance().getCommand(routeProperties);
        }
    }

    //提交任务
    @Override
    public void complete(RouteProperties routeProperties) {
        if (routeProperties == null || routeProperties.getQueues() == null || routeProperties.getQueues().isEmpty())
            return;
        RouteProperties before = BattleManager.getInstance().getRouteProperties(routeProperties.getPlayerId());
        if (before == null || before.getQueues() == null || before.getQueues().isEmpty()) return;

        // 获取已移除的任务列表
        List<Quest> removedQuests = new ArrayList<>();

        // 遍历之前的任务列表
        for (Quest beforeQuest : before.getQueues()) {
            boolean found = false;

            // 检查当前任务列表中是否还存在这个任务
            for (Quest currentQuest : routeProperties.getQueues()) {
                if (Objects.equals(beforeQuest.getName(), currentQuest.getName())) {
                    found = true;
                    break;
                }
            }

            // 如果在当前列表中没找到，则添加到已移除列表
            if (!found) {
                removedQuests.add(beforeQuest);
            }
        }

        // 处理已移除的任务
        if (!removedQuests.isEmpty()) {
            // 这里可以添加对已移除任务的处理逻辑
            for (Quest removedQuest : removedQuests) {
                TaskManager.getInstance().complete(routeProperties.getPlayerId(), removedQuest);
            }
        }
    }

    @Override
    public void gatherBlood(String playerId, List<Integer> bloods) {
        BattleManager.getInstance().updateBattleBloods(playerId, bloods);
    }

    @Override
    public void gatherEnemy(String playerId, List<Enemy> enemies) {
        BattleManager.getInstance().updateBattleEnemies(playerId, enemies);
    }

}
